<?php
namespace App\Services;

use App\Models\OrderComplain;
use App\Models\Store;
use App\Models\Tour;
use App\Models\TourExtra;
use App\Models\TourOrder;
use App\Models\TourOrderComplain;
use App\Models\TourOrderEvaluation;
use App\Models\TourOrderExtm;
use App\Models\TourOrderLog;
use App\Models\TourOrderTour;
use App\Models\TourSchedule;
use App\Models\TourSettings;
use App\Models\TourStatistics;
use App\Models\TourTuan;
use App\Models\TourTuanData;
use App\Models\Traveler;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 *
 * 线路订单服务层
 *
 * @author manong
 *
 */
class TourOrderService extends BaseService {
    //-------------------------------------add by shengl----------------
    /**
     * 获取订单出行人信息（姓名,身份证号码）
     * @auth shengl 2017年3月25日16:36:54
     * @param $user_id 下单用户id
     * @param $amount_a 出行成人人数
     * @param $amount_c 出行儿童人数
     * @param array $traveler_arr 出行人id数组
     * @return array
     */
    public function findTravelers($user_id,$traveler_arr=[]){
        $query = Traveler::where('user_id',$user_id);
        if(count($traveler_arr)>0){
            $query->whereIn('traveler_id',$traveler_arr);
        }
        $travelers=$query->select('traveler_name','id_card','is_child')->get();

        if(count($travelers) == 0){
            return $this->failure('请先添加出行人信息');
        }
        if(count($traveler_arr) != count($traveler_arr)){
            return $this->failure('请选择正确有效的出行人');
        }

        return $this->success($travelers);
    }

    /**
     * 获取日程库存信息（配置信息）
     * @auth shengl 2017年3月25日18:38:50
     * @param $tour_id 路线id
     * @param $schedule_id 日程id
     * @return array
     */
    public function getTourScheduleStock($tour_id,$schedule_id){
        $tourScheduleStock = TourSchedule::where('id',$schedule_id)->where('tour_id',$tour_id)->select('stock','saled_cnt')->first();

        if(!$tourScheduleStock){
            return $this->failure('未找到该日程');
        }

        return $this->success($tourScheduleStock);
    }

    /**
     * 获取路线扩展信息（图文信息除外）
     * @auth shengl 2017年3月25日18:39:30
     * @param $tour_id 路线id
     * @return array
     */
    public function getTourExtraInfo($tour_id){
        $tourExtra = TourExtra::where('tour_id',$tour_id)->select('options','travel_days','gather_time','gather_place')->first();

        if(!$tourExtra){
            return $this->failure('未找到该路线');
        }

        $tourExtra->options = json_decode($tourExtra->options);
        return $this->success($tourExtra);
    }

    /**
     *    生成订单号
     *
     *    @author    maqu
     *    @return    string
     */
    public function getOrderSn()
    {
        /*原规则 选择一个随机的方案*/
        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('Ymd', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = 'T'.$y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        /* 订单号新规则 */
//        $order_sn=date('YmdHis',time());
        $orders = TourOrder::where('order_sn',$order_sn)->get();
        if (count($orders) == 0)
        {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->getOrderSn();
    }

    /**
     *    获取单买订单状态相应的文字表述
     *
     *    @param     int $order_status  订单主状态
     *    @param     int $evaluation_status  评价状态
     *    @return    string
     */
    public function tourOrderStatus($order_status,$evaluation_status=0,$complain_status=0,$order_id=0)
    {
        $lang_key = '';
        switch ($order_status)
        {
            case TOUR_ORDER_PENDING:
                $lang_key = 'order_pending';
                break;
            case TOUR_ORDER_ACCEPTED:
                $lang_key = 'order_accepted';
                break;
            case TOUR_ORDER_AGREE:
                $lang_key = 'order_agree';
                break;
            case TOUR_ORDER_REFUNDING:
                $lang_key = 'order_refunding';
                break;
            case TOUR_ORDER_SUBMITTED:
                $lang_key = 'order_submitted';
                break;
            case TOUR_ORDER_FINISHED:
                switch($complain_status){

                    case 0://未投诉
                        if($evaluation_status==0){
                            $lang_key = 'waite_evaluation';
                        }else{
                            $lang_key = 'order_finished';
                        }
                        break;
                    case 1;//已投诉
                        $order_complain_status = DB::table('complain')
                            ->where('order_id',$order_id)
                            ->where('product_type','tour')
                            ->value('judge_state');
                        if($order_complain_status==0){
                            $lang_key = 'waite_handle';//已投诉，待处理
                        }elseif($order_complain_status==1){
                            $lang_key = 'complain_handle';//已投诉，处理中
                        }elseif($order_complain_status==2){//处理成功
                            if($evaluation_status==0){
                                $lang_key = 'waite_evaluation';
                            }else{
                                $lang_key = 'order_finished';
                            }
                        }
                        break;
                }
                break;
            case TOUR_ORDER_REFUND:
                $lang_key = 'order_refunded';
                break;
            case TOUR_ORDER_CANCELED:
                $lang_key = 'order_canceled';
                break;
            case TOUR_ORDER_DELETED:
                $lang_key = 'order_deleted';
        }

        $keyvalues = array(
            'waite_handle'     => '已投诉，待处理',
            'complain_handle'     => '投诉处理中',
            'order_pending'     => '待付款',
            'order_accepted'   => '待出行',
            'order_refunding' => '申请退款中',
            'order_agree'     => '卖家同意退款',
            'order_canceled'    => '已取消',
            'order_refunded'	=> '已退款',
            'order_finished'    => '已完成',
            'order_deleted'		=> '已删除',
            'waite_evaluation'  => '已完成,待评价',
            'order_submitted'  => '已付款待成团');

        return $lang_key  ? $keyvalues[$lang_key] : $lang_key;
    }

//获取团购订单对应的状态
    public function tourTuanStatus($order_status,$tuan_arr,$evaluation_status=0,$complain_status=0,$order_id=0)
    {
        $status =[
           'tuan_text' => '', //团状态描述
           'status_text' => ''//订单状态描述
        ];
        switch ($tuan_arr->state)
        {
            case TUAN_STATE_WAITE://组团中
                switch ($order_status)
                {
                    case TOUR_ORDER_SUBMITTED:// 针对拼团已付款，他的下一个状态是等待出行
                        $status['tuan_text'] = '组团中';
                        $status['status_text'] = '等待成团';
                        break;
                    case TOUR_ORDER_ACCEPTED:// 买家已付款，等待出行
                        $status['tuan_text'] = '组团中';
                        $status['status_text'] = '等待成团';
                        break;
                    case TOUR_ORDER_REFUNDING:// 处于退款流程中 申请退款中
                        $status['tuan_text'] = '申请退团';
                        $status['status_text'] = '申请退款中';
                        break;
                    case TOUR_ORDER_AGREE:// 合伙人同意退款 等待平台导出退款单退款
                        $status['tuan_text'] = '申请退团';
                        $status['status_text'] = '等待平台退款';
                        break;
                    case TOUR_ORDER_FINISHED: // 交易成功
                        $status['tuan_text'] = '组团成功';
                        $status['status_text'] = '已出行';
                        break;
                    case TOUR_ORDER_REFUND:// 退款成功
                        $status['tuan_text'] = '已退团';
                        $status['status_text'] = '退款成功';
                        break;
                    case TOUR_ORDER_CANCELED:// 交易已取消
                        $status['tuan_text'] = '';
                        $status['status_text'] = '已取消';
                        break;
                    case TOUR_ORDER_DELETED://订单删除
                        $status['tuan_text'] = '';
                        $status['status_text'] = '已删除';
                        break;
                }
                break;
            case TUAN_STATE_SUCCESS://组团成功
                switch ($order_status)
                {
                    case TOUR_ORDER_SUBMITTED:// 针对拼团已付款，他的下一个状态是等待出行
                        $status['tuan_text'] = '组团成功';
                        $status['status_text'] = '待出行';
                        break;
                    case TOUR_ORDER_ACCEPTED:// 买家已付款，等待出行
                        $status['tuan_text'] = '组团中';
                        $status['status_text'] = '待出行';
                        break;
                    case TOUR_ORDER_REFUNDING:// 处于退款流程中 申请退款中
                        $status['tuan_text'] = '申请退团';
                        $status['status_text'] = '申请退款中';
                        break;
                    case TOUR_ORDER_AGREE:// 合伙人同意退款 等待平台导出退款单退款
                        $status['tuan_text'] = '申请退团';
                        $status['status_text'] = '等待平台退款';
                        break;
                    case TOUR_ORDER_FINISHED: // 交易成功
                        switch($complain_status){

                            case 0://未投诉
                                if($evaluation_status==0){
                                    $status['tuan_text'] = '组团成功';
                                    $status['status_text'] = '已出行,待评价';
                                }else{
                                    $status['tuan_text'] = '组团成功';
                                    $status['status_text'] = '已出行';
                                }
                                break;
                            case 1;//已投诉
                                $order_complain_status = DB::table('complain')
                                    ->where('order_id',$order_id)
                                    ->where('product_type','tour')
                                    ->value('judge_state');
                                if($order_complain_status==0){
                                    $status['tuan_text'] = '组团成功';
                                    $status['status_text'] = '已投诉,待处理';;//已投诉，待处理
                                }elseif($order_complain_status==1){
                                    $status['tuan_text'] = '组团成功';
                                    $status['status_text'] = '已投诉,处理中';;//已投诉，处理中
                                }elseif($order_complain_status==2){//处理成功
                                    if($evaluation_status==0){
                                        $status['tuan_text'] = '组团成功';
                                        $status['status_text'] = '已出行,待评价';
                                    }else{
                                        $status['tuan_text'] = '组团成功';
                                        $status['status_text'] = '已出行';
                                    }
                                }
                                break;
                        }



                        break;
                    case TOUR_ORDER_REFUND:// 退款成功
                        $status['tuan_text'] = '已退团';
                        $status['status_text'] = '退款成功';
                        break;
                    case TOUR_ORDER_CANCELED:// 交易已取消
                        $status['tuan_text'] = '';
                        $status['status_text'] = '已取消';
                        break;
                    case TOUR_ORDER_DELETED://订单删除
                        $status['tuan_text'] = '';
                        $status['status_text'] = '已删除';
                        break;
                }
                break;
            case TUAN_STATE_FAILURE://组团失败
                switch ($order_status)
                {
                    case TOUR_ORDER_SUBMITTED:// 针对拼团已付款，他的下一个状态是等待出行
                        $status['tuan_text'] = '组团失败';
                        $status['status_text'] = '等待平台退款';
                        break;
                    case TOUR_ORDER_PENDING:// 等待买家付款
                        $status['tuan_text'] = '组团失败';
                        $status['status_text'] = '待付款';
                        break;
                    case TOUR_ORDER_ACCEPTED:// 买家已付款，等待出行
                        $status['tuan_text'] = '组团失败';
                        $status['status_text'] = '等待平台退款';
                        break;
                    case TOUR_ORDER_REFUND:// 退款成功
                        $status['tuan_text'] = '已退团';
                        $status['status_text'] = '退款成功';
                        break;
                    case TOUR_ORDER_CANCELED:// 交易已取消
                        $status['tuan_text'] = '';
                        $status['status_text'] = '已取消';
                        break;
                    case TOUR_ORDER_DELETED://订单删除
                        $status['tuan_text'] = '';
                        $status['status_text'] = '已删除';
                        break;
                    case TOUR_ORDER_AGREE:// 合伙人同意退款 等待平台导出退款单退款
                        $status['tuan_text'] = '组团失败';
                        $status['status_text'] = '等待平台退款';
                        break;
                }
                break;
        }
        return $status;
    }

    /**添加订单操作日志
     * @param $order_id 订单id
     * @param $user_name 操作者用户名
     * @param $old_status 订单原先状态
     * @param $new_status 操作后的订单撞他
     * @param $remark 操作原因
     * @param bool/false $withTrans 是否单独开启事务
     */
    public function addTourOrderLog($order_id,$user_name,$old_status,$new_status,$remark,$withTrans = false){
        if($withTrans){
            DB::beginTransaction();
        }
        try{
            $tourOrderLog = new TourOrderLog();
            $tourOrderLog->order_id = $order_id;
            $tourOrderLog->operator = addslashes($user_name);
            $tourOrderLog->order_status = $old_status;
            $tourOrderLog->changed_status = $new_status;
            $tourOrderLog->remark = $remark;
            $tourOrderLog->log_time = gmtime();

            $tourOrderLog->save();
            if($withTrans){
                DB::commit();
            }
        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
        }


    }

    /**单人购买旅游路线下单创建订单
     * @param $user_id 下单用户id
     * @param $tour_id 路线id
     * @param $schedule_id 日程id
     * @param $amount_a 成年人数量
     * @param $amount_c 儿童数量
     * @param $options 已选的额外服务
     * @param $travelers 出行人
     * @param \stdClass $linkman 联系人
     * @param bool|true $withTrans
     * @return array
     */
    public function createSingleOrder($user_id,$tour_id,$schedule_id,$amount_a,$amount_c,$options,$travelers,\stdClass $linkman,$withTrans = true){
        //买家用户信息
        $userInfo = User::find($user_id);

        //旅行线路信息
        $tourInfo = Tour::with(['tourExtra'=>function($query){
            $query->select('tour_id','options','travel_days','gather_time','gather_place');
        }])->find($tour_id);

        if(!$tourInfo->allow_singlebuy){
            return $this->failure('该旅游路线不可单独购买');
        }

        switch($tourInfo->adult_child_joinflg){
            case TOUR_JOIN_ADULT_ONLY:
                if($amount_c > 0 ){
                    return $this->failure('该旅游路线只允许成人出行');
                }
                $quantity = $amount_a;
                break;
            case TOUR_JOIN_CHILD_ONLY:
                if($amount_a > 0){
                    return $this->failure('该旅游路线只允许儿童出行');
                }
                $quantity = $amount_c;
                break;
            default:
                $quantity = $amount_a;
        }

        $tourSchedule = TourSchedule::where('tour_id',$tour_id)->find($schedule_id);
        if(!$tourSchedule){
            return $this->failure('未找到该线路的日程');
        }

        //查找该路线剩余人数
        if($quantity > $tourSchedule->stock){
            return $this->failure('剩余出行人数不足，请减少出行人数');
        }

        //出行前多少天可以购买
        $stopsale_days = TourSettings::where('tour_id',$tour_id)->value('stopsale_days');
        $rest_time = strtotime(local_date_ymd($tourSchedule->open_date))-strtotime(local_date_ymd(gmtime()));
        $rest_date = $rest_time/86400;
        if($stopsale_days>$rest_date){
            return $this->failure('该日程已经停止购买');
        }

        //店铺名称(乡村名称)
        $seller_name = Store::where('store_id',$tourInfo->store_id)->value('store_name');

        $singlebuy_config = json_decode($tourSchedule->singlebuy_config);

        //计算人数价格
        $traveler_money = $amount_a*$singlebuy_config->price_a + $amount_c*$singlebuy_config->price_c;

        //计算附加项目金额
        $options_json = json_decode($options);
        $tourOptions = json_decode($tourInfo->tourExtra->options);
        $options_money = 0;
        $chosed_options= [];
        if($options_json){
            foreach($tourOptions as $item){
                foreach($options_json as $chosed){
                    if($chosed->tservice_id == $item->tservice_id){
                        $options_money += $chosed->tservice_amount*$item->defined_price;
                        $item->tservice_amount = $chosed->tservice_amount;
                        $chosed_options[] = $item;
                        break;
                    }
                }
            }
        }

        $all_money = $traveler_money + $options_money;

        if($withTrans){
            DB::beginTransaction();
        }
        try{
            //插入订单数据
            $tourOrder = new TourOrder();
            //订单编号
            $tourOrder->order_sn = self::getOrderSn();
            //下单类型
            $tourOrder->extension = TOUR_ORDER_EXTENSION_NORMAL;
            //店铺（乡村）id
            $tourOrder->seller_id = $tourInfo->store_id;
            //店铺（乡村）名称
            $tourOrder->seller_name = $seller_name;
            //买家用户id
            $tourOrder->buyer_id = $user_id;
            //买家用户昵称
            $tourOrder->buyer_name = $userInfo->nickname;
            //买家联系email
            $tourOrder->buyer_email = $userInfo->email;
            //订单状态
            $tourOrder->status = ORDER_PENDING;
            //下单时间
            $tourOrder->add_time = gmtime();
            //订单出行人总价
            $tourOrder->travelers_amount = $traveler_money;
            //订单额外服务总价
            $tourOrder->options_amount = $options_money;
            //订单总价
            $tourOrder->order_amount = $all_money;
            //给店铺留言
            $tourOrder->postscript = $linkman->postscript;
            //订单来源
            $tourOrder->order_from = ORDER_FROM_WAP;

            $tourOrder->save();

            $tourOrderExtm = new TourOrderExtm();
            //订单id
            $tourOrderExtm->order_id = $tourOrder->order_id;
            //订单联系人姓名
            $tourOrderExtm->linkman_name = $linkman->linkman_name;
            //订单联系人电话
            $tourOrderExtm->linkman_phone = $linkman->linkman_phone;
            //出行人信息
            $tourOrderExtm->travel_peoples = $travelers->toJson();

            $tourOrderExtm->save();

            $tourOrderTour = new TourOrderTour();
            //订单id
            $tourOrderTour->order_id = $tourOrder->order_id;
            //路线id
            $tourOrderTour->tour_id = $tour_id;
            //日程id
            $tourOrderTour->schedule_id = $schedule_id;
            //路线编号
            $tourOrderTour->tour_sn = $tourInfo->tour_sn;
            //路线名称
            $tourOrderTour->tour_name = $tourInfo->tour_name;
            //路线默认图
            $tourOrderTour->tour_image = $tourInfo->default_image;
            //出发地
            $tourOrderTour->from_region_name = $tourInfo->from_region_name;
            //目的地
            $tourOrderTour->to_region_name = $tourInfo->to_region_name;
            //出行日期
            $tourOrderTour->open_date = $tourSchedule->open_date;
            //单买配置
            $tourOrderTour->singlebuy_config = $tourSchedule->singlebuy_config;
            //团购配置
            $tourOrderTour->groupbuy_config = $tourSchedule->groupbuy_config;
            //额外服务
            $tourOrderTour->options = json_encode($chosed_options);
            //旅行天数
            $tourOrderTour->travel_days = $tourInfo->tourExtra->travel_days;
            //集合时间
            $tourOrderTour->gather_time = $tourInfo->tourExtra->gather_time;
            //集合地点
            $tourOrderTour->gather_place = $tourInfo->tourExtra->gather_place;
            //订单出行成人人数
            $tourOrderTour->peoples_a = $amount_a;
            //订单出行儿童人数
            $tourOrderTour->peoples_c = $amount_c;
            //订单所占库存数量
            $tourOrderTour->quantity = $quantity;
            //线路所允许出行人类型
            $tourOrderTour->adult_child_joinflg = $tourInfo->adult_child_joinflg;

            $tourOrderTour->save();

            //订单日志
            $new_status = self::tourOrderStatus(TOUR_ORDER_PENDING);
            self::addTourOrderLog($tourOrder->order_id,$userInfo->nickname,'用户创建订单',$new_status,'用户下单',false);

            if($withTrans) {
                DB::commit();
            }

            return $this->success($tourOrder);

        } catch(\Exception $e){
            if($withTrans) {
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('下单失败');

        }

    }

    /**
     * 创建合买并下单
     * @param $user_id
     * @param $tour_id
     * @param $schedule_id
     * @param $copy_peoples
     * @param $tuan_type
     * @param string $tuan_password
     * @param $copies
     * @param $slogan
     * @param $traveler_arr
     * @param \stdClass $linkman
     * @param bool|true $withTrans
     * @return array
     */
    public function createGroupOrder($user_id,$tour_id,$schedule_id,$copy_peoples,$tuan_type,$tuan_password='',$copies,$slogan,$traveler_arr,\stdClass $linkman,$withTrans = true){

        //买家用户信息
        $userInfo = User::find($user_id);

        //旅行线路信息
        $tourInfo = Tour::with(['tourExtra'=>function($query){
            $query->select('tour_id','travel_days','gather_time','gather_place');
        }])->find($tour_id);

        if(!$tourInfo->allow_groupbuy){
            return $this->failure('该旅游路线不可团购');
        }

        $tourSchedule = TourSchedule::where('tour_id',$tour_id)->find($schedule_id);
        if(!$tourSchedule){
            return $this->failure('未找到该线路的日程');
        }

        //获取出行人信息
        $travelersData = self::findTravelers($user_id,$traveler_arr);
        if(!$travelersData['result']){
            return $this->failure($travelersData['msg']);
        }
        //出行人信息
        $travelers = $travelersData['data'];

        //计算出行的成人和儿童数量
        $amount_a = 0;
        $amount_c = 0;
        foreach($travelers as $item){
            if($item->is_child){
                $amount_c ++;
            }else{
                $amount_a ++;
            }
        }

        $groupbuy_config = json_decode($tourSchedule->groupbuy_config);
        $tourSchedule->stock = $tourSchedule->stock_defined - $tourSchedule->saled_cnt;
        //判断出行人是否符合规范
        switch($tourInfo->adult_child_joinflg){
            case TOUR_JOIN_ADULT_ONLY:
                if($amount_c > 0 ){
                    return $this->failure('该旅游路线只允许成人出行');
                }

                if($amount_a > ($copies * $groupbuy_config->limit_a)){
                    return $this->failure('出行人数超出限制');
                }

                //查找该路线剩余人数
                if(($copy_peoples * $groupbuy_config->limit_a) > $tourSchedule->stock){
                    return $this->failure('该日程剩余出行人数不足，无法开团。请减少团人数或者选择其他日程');
                }

                $quantity = $copies * $groupbuy_config->limit_a;
                break;
            case TOUR_JOIN_CHILD_ONLY:
                if($amount_a > 0){
                    return $this->failure('该旅游路线只允许儿童出行');
                }

                if($amount_c > ($copies * $groupbuy_config->limit_c)){
                    return $this->failure('出行人数超出限制');
                }

                //查找该路线剩余人数
                if(($copies * $groupbuy_config->limit_c) > $tourSchedule->stock){
                    return $this->failure('该日程剩余出行人数不足，无法开团。请减少团人数或者选择其他日程');
                }

                $quantity = $copies * $groupbuy_config->limit_c;
                break;
            default:
                if($amount_a > ($copies * $groupbuy_config->limit_a) || $amount_c > ($copies * $groupbuy_config->limit_c)){

                    return $this->failure('出行人数超出限制');
                }

                if($amount_a < ($copies * $groupbuy_config->limit_a) || $amount_c < ($copies * $groupbuy_config->limit_c)){

                    return $this->failure('请继续添加出行人');
                }

                //查找该路线剩余人数
                if(($copies * ($groupbuy_config->limit_a + $groupbuy_config->limit_c)) > $tourSchedule->stock){
                    return $this->failure('该日程剩余出行人数不足，无法开团。请减少团人数或者选择其他日程');
                }

                $quantity = $copies * ($groupbuy_config->limit_a + $groupbuy_config->limit_c) ;
        }

        //出行前多少天可以购买
        $stopsale_days = TourSettings::where('tour_id',$tour_id)->value('stopsale_days');
        $rest_time = strtotime(local_date_ymd($tourSchedule->open_date))-strtotime(local_date_ymd(gmtime()));
        $rest_date = $rest_time/86400;
        if($stopsale_days>$rest_date){
            return $this->failure('该日程已经停止购买');
        }

        //店铺名称(乡村名称)
        $seller_name = Store::where('store_id',$tourInfo->store_id)->value('store_name');

        $copy_price = 0;
        foreach($groupbuy_config->prices as $item){
            if($copy_peoples == $item->peoples){
                $copy_price = $item->price;
                break;
            }
        }

        //每份的限制配置
        $copy_config = [
            'limit_a' => $groupbuy_config->limit_a,
            'limit_c' => $groupbuy_config->limit_c
        ];

        //计算人数价格
        $traveler_money = $copies*$copy_price;
        //团购无其他额外服务
        $options_money = 0;
        //总价
        $all_money = $traveler_money+$options_money;

        //团失效时间为可购买的最后时间
        $end_timeconfig =new ConfigService();

        $tuan_info_endtime = $end_timeconfig->getConfig('tuan_info_endtime');

        if($withTrans){
            DB::beginTransaction();
        }
        try{

            //创建拼团数据
            $tourTuan = new TourTuan();
            $tourTuan->tour_id = $tour_id;
            $tourTuan->schedule_id = $schedule_id;
            $tourTuan->tuanzhang = $user_id;
            $tourTuan->slogan = $slogan;
            $tourTuan->state = TUAN_STATE_DEFAULT;
            $tourTuan->start_time = gmtime();
            $tourTuan->end_time = (($tuan_info_endtime*24*3600 + $tourTuan->start_time)>= $tourSchedule->open_date)?$tourSchedule->open_date : $tuan_info_endtime*24*3600 + $tourTuan->start_time;
            $tourTuan->copy_tour_date = $tourSchedule->open_date;
            $tourTuan->copy_peoples = $copy_peoples*($groupbuy_config->limit_a + $groupbuy_config->limit_c);
            $tourTuan->copy_price = $copy_price;
            $tourTuan->tuan_type = $tuan_type;
            $tourTuan->pwd = md5($tuan_password);
            $tourTuan->rest_copies = $copy_peoples*($groupbuy_config->limit_a + $groupbuy_config->limit_c);
            $tourTuan->copy_config = json_encode($copy_config);

            $tourTuan->save();

            //插入订单数据
            $tourOrder = new TourOrder();
            //订单编号
            $tourOrder->order_sn = self::getOrderSn();
            //下单类型
            $tourOrder->extension = TOUR_ORDER_EXTENSION_GROUPBUY;
            //店铺（乡村）id
            $tourOrder->seller_id = $tourInfo->store_id;
            //店铺（乡村）名称
            $tourOrder->seller_name = $seller_name;
            //买家用户id
            $tourOrder->buyer_id = $user_id;
            //买家用户昵称
            $tourOrder->buyer_name = $userInfo->nickname;
            //买家联系email
            $tourOrder->buyer_email = $userInfo->email;
            //订单状态
            $tourOrder->status = ORDER_PENDING;
            //下单时间
            $tourOrder->add_time = gmtime();
            //订单出行人总价
            $tourOrder->travelers_amount = $traveler_money;
            //订单额外服务总价
            $tourOrder->options_amount = $options_money;
            //订单总价
            $tourOrder->order_amount = $all_money;
            //给店铺留言
            $tourOrder->postscript = $linkman->postscript;
            //订单来源
            $tourOrder->order_from = ORDER_FROM_WAP;

            $tourOrder->tuan_id = $tourTuan->tuan_id;

            $tourOrder->save();

            $tourOrderExtm = new TourOrderExtm();
            //订单id
            $tourOrderExtm->order_id = $tourOrder->order_id;
            //订单联系人姓名
            $tourOrderExtm->linkman_name = $linkman->linkman_name;
            //订单联系人电话
            $tourOrderExtm->linkman_phone = $linkman->linkman_phone;
            //出行人信息
            $tourOrderExtm->travel_peoples = $travelers->toJson();

            $tourOrderExtm->save();

            $tourOrderTour = new TourOrderTour();
            $tourOrderTour->order_id = $tourOrder->order_id;
            $tourOrderTour->tour_id = $tour_id;
            $tourOrderTour->schedule_id = $schedule_id;
            $tourOrderTour->tour_sn = $tourInfo->tour_sn;
            $tourOrderTour->tour_name = $tourInfo->tour_name;
            $tourOrderTour->tour_image = $tourInfo->default_image;
            $tourOrderTour->from_region_name = $tourInfo->from_region_name;
            $tourOrderTour->to_region_name = $tourInfo->to_region_name;
            $tourOrderTour->open_date = $tourSchedule->open_date;
            $tourOrderTour->singlebuy_config = $tourSchedule->singlebuy_config;
            $tourOrderTour->groupbuy_config = $tourSchedule->groupbuy_config;
            $tourOrderTour->travel_days = $tourInfo->tourExtra->travel_days;
            $tourOrderTour->gather_time = $tourInfo->tourExtra->gather_time;
            $tourOrderTour->gather_place = $tourInfo->tourExtra->gather_place;
            $tourOrderTour->peoples_a = $amount_a;
            $tourOrderTour->peoples_c = $amount_c;
            $tourOrderTour->quantity = $quantity;
            $tourOrderTour->adult_child_joinflg = $tourInfo->adult_child_joinflg;

            $tourOrderTour->save();

            $tourTuanData = new TourTuanData();
            $tourTuanData->tuan_id = $tourTuan->tuan_id;
            $tourTuanData->user_id = $user_id;
            $tourTuanData->order_id = $tourOrder->order_id;
            $tourTuanData->add_time = gmtime();
            $tourTuanData->copies = $copies;
            $tourTuanData->quantity = $quantity;
            $tourTuanData->nickname = $userInfo->nickname;
            $tourTuanData->portrait = $userInfo->portrait;
            $tourTuanData->state = TUAN_STATE_WAITE;

            $tourTuanData->save();

            //订单日志
            $new_status = self::tourOrderStatus(TOUR_ORDER_PENDING);
            self::addTourOrderLog($tourOrder->order_id,$userInfo->nickname,'用户创建订单',$new_status,'用户团购开团下单',false);

            if($withTrans) {
                DB::commit();
            }
            return $this->success($tourOrder);

        } catch(\Exception $e){
            if($withTrans) {
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('下单失败');

        }
    }

    public function joinGroupOrder($user_id,$tuan_id,$tuan_password='',$copies,$traveler_arr,\stdClass $linkman,$withTrans = true){

        //买家用户信息
        $userInfo = User::find($user_id);

        $tourTuan = TourTuan::with([
            'tour'=>function($query){
            $query->select('tour_id','store_id','tour_sn','tour_name','short_name','default_image','allow_groupbuy','adult_child_joinflg','tags','from_region_name','to_region_name');
        },'tour.tourExtra'=>function($query){
            $query->select('tour_id','travel_days','gather_time','gather_place');
        },'tourSchedule'=>function($query){
            $query->select('id','open_date','singlebuy_config','groupbuy_config');
        },'tourTuanData'=>function($query){
            $query->where('state',TUAN_DATA_STATE_SUCCESS)->select('tuan_id','user_id','nickname','portrait');
        }])->select('tuan_id','tour_id','schedule_id','slogan','tuanzhang','start_time','end_time','rest_copies','copy_price','tuan_type','copy_config','pwd','state')->find($tuan_id);

        if(!$tourTuan){
            return $this->failure('该路线占无人员开启团购');
        }

        switch($tourTuan->state){
            case TUAN_STATE_DEFAULT:
                return $this->failure('该团购尚未开启,无法参与');
                break;
            case TUAN_STATE_FAILURE:
                return $this->failure('该团购已失败,无法参与');
                break;
            case TUAN_STATE_SUCCESS:
                return $this->failure('该团购已完成,无法参与');
                break;
            case TUAN_STATE_WAITE:
                if($tourTuan->endtime <= gmtime()){
                    return $this->failure('该团购已过期,无法参与');
                }
                break;
        }

        foreach($tourTuan->tourTuanData as $item){
            if($user_id == $item->user_id){
                return $this->failure('您已参加过该次团购,无法继续参团');
            }
            unset($item->tuan_id,$item->user_id);
            $item->portrait = complete_url($item->portrait);
        }

        if(!$tourTuan->tour->allow_groupbuy){
            return $this->failure('该旅游路线已不可团购');
        }

        if($tourTuan->tuan_type == TOUR_TUAN_TYPE_PRIVATE && $tourTuan->pwd != md5($tuan_password) ){
            return $this->failure('参团密码不正确，您无法参与该团');
        }
        $mpeoples = json_decode($tourTuan->tourSchedule->groupbuy_config,true);//获取每份限制人数

        if($copies *($mpeoples['limit_a'] + $mpeoples['limit_c']) > $tourTuan->rest_copies){
            return $this->failure('团购购买的份数不足');
        }

        //获取出行人信息
        $travelersData = self::findTravelers($user_id,$traveler_arr);
        if(!$travelersData['result']){
            return $this->failure($travelersData['msg']);
        }
        //出行人信息
        $travelers = $travelersData['data'];

        //计算出行的成人和儿童数量
        $amount_a = 0;
        $amount_c = 0;
        foreach($travelers as $item){
            if($item->is_child){
                $amount_c ++;
            }else{
                $amount_a ++;
            }
        }

        $copy_config = json_decode($tourTuan->copy_config);

        //判断出行人是否符合规范
        switch($tourTuan->tour->adult_child_joinflg){
            case TOUR_JOIN_ADULT_ONLY:
                if($amount_c > 0 ){
                    return $this->failure('该旅游路线只允许成人出行');
                }

                if($amount_a > ($copies * $copy_config->limit_a)){
                    return $this->failure('人数超出限制');
                }

                $quantity = $amount_a;
                break;
            case TOUR_JOIN_CHILD_ONLY:
                if($amount_a > 0){
                    return $this->failure('该旅游路线只允许儿童出行');
                }

                if($amount_c > ($copies * $copy_config->limit_c)){
                    return $this->failure('人数超出限制');
                }

                $quantity = $amount_c;
                break;
            default:
                if($amount_a > ($copies * $copy_config->limit_a) || $amount_c > ($copies * $copy_config->limit_c)){
                    return $this->failure('人数超出限制');
                }

                if($amount_a < ($copies * $copy_config->limit_a) || $amount_c < ($copies * $copy_config->limit_c)){
                    return $this->failure('请继续添加出行人');
                }

                $quantity =$copies * ($copy_config->limit_a + $copy_config->limit_c);
        }

        //店铺名称(乡村名称)
        $seller_name = Store::where('store_id',$tourTuan->tour->store_id)->value('store_name');

        //计算人数价格
        $traveler_money = $copies*$tourTuan->copy_price;
        //团购无其他额外服务
        $options_money = 0;
        //总价
        $all_money = $traveler_money+$options_money;

        if($withTrans){
            DB::beginTransaction();
        }
        try{
            //插入订单数据
            $tourOrder = new TourOrder();
            //订单编号
            $tourOrder->order_sn = self::getOrderSn();
            //下单类型
            $tourOrder->extension = TOUR_ORDER_EXTENSION_GROUPBUY;
            //店铺（乡村）id
            $tourOrder->seller_id = $tourTuan->tour->store_id;
            //店铺（乡村）名称
            $tourOrder->seller_name = $seller_name;
            //买家用户id
            $tourOrder->buyer_id = $user_id;
            //买家用户昵称
            $tourOrder->buyer_name = $userInfo->nickname;
            //买家联系email
            $tourOrder->buyer_email = $userInfo->email;
            //订单状态
            $tourOrder->status = ORDER_PENDING;
            //下单时间
            $tourOrder->add_time = gmtime();
            //订单出行人总价
            $tourOrder->travelers_amount = $traveler_money;
            //订单额外服务总价
            $tourOrder->options_amount = $options_money;
            //订单总价
            $tourOrder->order_amount = $all_money;
            //给店铺留言
            $tourOrder->postscript = $linkman->postscript;
            //订单来源
            $tourOrder->order_from = ORDER_FROM_WAP;

            $tourOrder->tuan_id = $tourTuan->tuan_id;

            $tourOrder->save();

            $tourOrderExtm = new TourOrderExtm();
            //订单id
            $tourOrderExtm->order_id = $tourOrder->order_id;
            //订单联系人姓名
            $tourOrderExtm->linkman_name = $linkman->linkman_name;
            //订单联系人电话
            $tourOrderExtm->linkman_phone = $linkman->linkman_phone;
            //出行人信息
            $tourOrderExtm->travel_peoples = $travelers->toJson();

            $tourOrderExtm->save();

            $tourOrderTour = new TourOrderTour();
            $tourOrderTour->order_id = $tourOrder->order_id;
            $tourOrderTour->tour_id = $tourTuan->tour_id;
            $tourOrderTour->schedule_id = $tourTuan->schedule_id;
            $tourOrderTour->tour_sn = $tourTuan->tour->tour_sn;
            $tourOrderTour->tour_name = $tourTuan->tour->tour_name;
            $tourOrderTour->tour_image = $tourTuan->tour->default_image;
            $tourOrderTour->from_region_name = $tourTuan->tour->from_region_name;
            $tourOrderTour->to_region_name = $tourTuan->tour->to_region_name;
            $tourOrderTour->open_date = $tourTuan->tourSchedule->open_date;
            $tourOrderTour->singlebuy_config = $tourTuan->tourSchedule->singlebuy_config;
            $tourOrderTour->groupbuy_config = $tourTuan->tourSchedule->groupbuy_config;
            $tourOrderTour->travel_days = $tourTuan->tour->tourExtra->travel_days;
            $tourOrderTour->gather_time = $tourTuan->tour->tourExtra->gather_time;
            $tourOrderTour->gather_place = $tourTuan->tour->tourExtra->gather_place;
            $tourOrderTour->peoples_a = $amount_a;
            $tourOrderTour->peoples_c = $amount_c;
            $tourOrderTour->quantity = $quantity;
            $tourOrderTour->adult_child_joinflg = $tourTuan->tour->adult_child_joinflg;

            $tourOrderTour->save();

            $tourTuanData = new TourTuanData();
            $tourTuanData->tuan_id = $tourTuan->tuan_id;
            $tourTuanData->user_id = $user_id;
            $tourTuanData->order_id = $tourOrder->order_id;
            $tourTuanData->add_time = gmtime();
            $tourTuanData->copies = $copies;
            $tourTuanData->quantity = $quantity;
            $tourTuanData->nickname = $userInfo->nickname;
            $tourTuanData->portrait = $userInfo->portrait;
            $tourTuanData->state = TUAN_STATE_WAITE;

            $tourTuanData->save();

            //订单日志
            $new_status = self::tourOrderStatus(TOUR_ORDER_PENDING);
            self::addTourOrderLog($tourOrder->order_id,$userInfo->nickname,'用户创建订单',$new_status,'用户团购参团下单',false);

            if($withTrans) {
                DB::commit();
            }

            return $this->success($tourOrder);

        } catch(\Exception $e){
            if($withTrans) {
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('下单失败');

        }
    }

    public function updateTuanState($order_id,$tuan_id,$withTrans = false){

        if($withTrans){
            DB::beginTransaction();
        }
        try{
            $tourTuanData = TourTuanData::where('order_id',$order_id)->first();
            $order_info = TourOrder::find($order_id);
            $tourTuan = TourTuan::find($tuan_id);
            switch($tourTuan->state){
                case TUAN_STATE_DEFAULT://如果团状态是待支付 支付成功修改为组团中
                    $tourTuan->state = TUAN_STATE_WAITE;
                    if($tourTuanData->quantity >= $tourTuan->rest_copies ){ //如果购买的份数大于等于 剩余份数 团成功
                        $tourTuan->state = TUAN_STATE_SUCCESS;
                        $tourTuan->succeed_time = gmtime();
                        $tourTuan->rest_copies = 0;
                        DB::table('tour_order')
                            ->where('order_id',$order_id)
                            ->update(['status'=>TOUR_ORDER_ACCEPTED]);
                    }else{//购买份数小于剩余份数
                        $tourTuan->rest_copies -= $tourTuanData->quantity;
                    }
                    break;
                case TUAN_STATE_WAITE: //如果团状态是组团中 判断是否成团
                    if($tourTuanData->quantity >= $tourTuan->rest_copies ){ //如果购买的份数大于等于 剩余份数 团成功
                        $tourTuan->state = TUAN_STATE_SUCCESS;
                        $tourTuan->succeed_time = gmtime();
                        $tourTuan->rest_copies = 0;
                        DB::table('tour_order')
                            ->where('order_id',$order_id)
                            ->update(['status'=>TOUR_ORDER_ACCEPTED]);
                    }else{//购买份数小于剩余份数
                        $tourTuan->rest_copies -= $tourTuanData->quantity;
                    }
                    break;
                case TUAN_STATE_SUCCESS://付款完成时团已创建成功 无法加入该团 给用户退款
                    //创建线路退款单
                    //退款单创建
                    $tour_order_refund = [
                        'order_id'=>$order_info->order_id,
                        'applier'=>'0',
                        'apply_date'=>gmtime(),
                        'apply_reason'=>'组团失败',
                        'receiver'=>'0',
                        'refund_status'=> TOUR_REFUND_REFUNDING,
                        'refund_remarks'=>'组团失败',
                        'last_time'=>gmtime(),
                        'refund_fee'=>$order_info->order_amount,
                        'tuan_id'=>$order_info->tuan_id,
                        'added_by_batch'=>1
                    ];

                    $refund_id = DB::table('tour_order_refund')->insertGetId($tour_order_refund);

                    //操作日志
                    $tour_order_refund_log = [
                        'refund_id'=> $refund_id,
                        'operator'=>'0',
                        'refund_status'=> '组团失败自动退款',
                        'changed_status'=> '退款中',
                        'remark'=>'组团失败系统自动生成',
                        'log_time'=>gmtime(),
                    ];

                    DB::table('tour_order_refund_log')->insert($tour_order_refund_log);

                    //更改订单状态
                    DB::table('tour_order')
                        ->where('order_id',$order_info->order_id)
                        ->update([
                            'status' => TOUR_ORDER_AGREE,//同意退款 等待退款
                        ]);

                    /* 操作记录 */
                    $order_log = [
                        'order_id'  => $order_info->order_id,
                        'operator'  => '0',
                        'order_status' => '组团中',
                        'changed_status' =>'组团失败退款' ,
                        'remark'    => '系统给组团失败订单退款',
                        'log_time'  => gmtime(),
                    ];

                    DB::table('tour_order_log')->insert($order_log);

                    break;
                case TUAN_STATE_FAILURE://付款完成时团已失败 无法加入该团 给用户退款
                    //创建线路退款单
                    //退款单创建
                    $tour_order_refund = [
                        'order_id'=>$order_info->order_id,
                        'applier'=>'0',
                        'apply_date'=>gmtime(),
                        'apply_reason'=>'组团失败',
                        'receiver'=>'0',
                        'refund_status'=> TOUR_REFUND_REFUNDING,
                        'refund_remarks'=>'组团失败',
                        'last_time'=>gmtime(),
                        'refund_fee'=>$order_info->order_amount,
                        'tuan_id'=>$order_info->tuan_id,
                        'added_by_batch'=>1
                    ];

                    $refund_id = DB::table('tour_order_refund')->insertGetId($tour_order_refund);

                    //操作日志
                    $tour_order_refund_log = [
                        'refund_id'=> $refund_id,
                        'operator'=>'0',
                        'refund_status'=> '组团失败自动退款',
                        'changed_status'=> '退款中',
                        'remark'=>'组团失败系统自动生成',
                        'log_time'=>gmtime(),
                    ];

                    DB::table('tour_order_refund_log')->insert($tour_order_refund_log);

                    //更改订单状态
                    DB::table('tour_order')
                        ->where('order_id',$order_info->order_id)
                        ->update([
                            'status' => TOUR_ORDER_AGREE,//同意退款 等待退款
                        ]);

                    /* 操作记录 */
                    $order_log = [
                        'order_id'  => $order_info->order_id,
                        'operator'  => '0',
                        'order_status' => '组团中',
                        'changed_status' =>'组团失败退款' ,
                        'remark'    => '系统给组团失败订单退款',
                        'log_time'  => gmtime(),
                    ];

                    DB::table('tour_order_log')->insert($order_log);
                    break;

            }
            $tourTuan->save();
            $tourTuanData->state = TUAN_DATA_STATE_SUCCESS;
            $tourTuanData->save();

            if($withTrans) {
                DB::commit();
            }

        } catch(\Exception $e){
            if($withTrans) {
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
        }

    }

    public function getTuanQuantity($tuan_id){
        $tourTuan = TourTuan::with(['tourTuanData'=>function($query){
            $query->select('tuan_id','quantity');
        }])->where('state',TUAN_STATE_SUCCESS)->find($tuan_id);

        if(!$tourTuan){
            $quantity = 0;
        }else{
            $quantity_array = array_column($tourTuan->tourTuanData->toArray(),'quantity');
            $quantity = array_sum($quantity_array);
        }
        return $this->success($quantity);



    }

    /**
     * 获取用户订单列表
     * @param $user_id
     * @param string $order_state
     * @param int $firstrow
     * @param int $pagesize
     * @return array
     */
    public function getTourOrderList($user_id,$order_state='all',$firstrow=0,$pagesize=10){

        //获取订单列表数据
        $query = TourOrder::where('buyer_id',$user_id)->where("delflg_buyer",NO);

        switch($order_state){
            case 'pending':
                $query->where('status',TOUR_ORDER_PENDING);
                break;
            case 'accepted':
                $query->where('status',TOUR_ORDER_ACCEPTED);
                break;
            case 'waite_evaluate':
                $query->where('status',TOUR_ORDER_FINISHED)->where('evaluation_status',NO);
                break;
            default:;
        }

        $orderList = $query->with(['tourOrderTour'=>function($query){
            $query->select('order_id','tour_id','schedule_id','tour_name','tour_image','open_date','peoples_a','peoples_c','singlebuy_config','groupbuy_config','options');
        },'tourTuanData'=>function($query){
            $query->select('order_id','copies','tuan_id');
        },'tourTuanData.tourTuan'=>function($query){
            $query->select('tuan_id','copy_price','state');
        }])
            ->select('order_id','extension','seller_id','seller_name','status','travelers_amount','options_amount','order_amount','evaluation_status','complain_status')->orderBy('order_id', 'desc')
            ->skip($firstrow)->take($pagesize)->get();

        if(!$orderList){
            return $this->failure('未找到对应的订单数据');
        }

        foreach($orderList as $item) {
            $item->tourOrderTour->open_date_fmt = local_date_ymd($item->tourOrderTour->open_date);
            $item->tourOrderTour->tour_image = complete_url($item->tourOrderTour->tour_image);
            $item->tourOrderTour->singlebuy_config = json_decode($item->tourOrderTour->singlebuy_config);
            $item->tourOrderTour->groupbuy_config = json_decode($item->tourOrderTour->groupbuy_config);
            $item->tourOrderTour->options = json_decode($item->tourOrderTour->options);
            if ($item->extension == 'groupbuy') { //团购订单显示状态由团状态控制
                $tuan_order_text = self::tourTuanStatus($item->status,$item->tourTuanData->tourTuan,$item->evaluation_status,$item->complain_status,$item->order_id);
                $item->tuan_text = $tuan_order_text['tuan_text'];
                $item->status_text = $tuan_order_text['status_text'];
                $item->tuan_state = $item->tourTuanData->tourTuan->state;
            } else {
                $item->status_text = self::tourOrderStatus($item->status,$item->evaluation_status,$item->complain_status,$item->order_id);
            }
            $item->ican = self::tourOrder_ican($item);
        }
        return $this->success($orderList);
    }

    private function tourOrder_ican($tourOrder){

        $order_status =$tourOrder['status'];
        $evaluation_status=$tourOrder['evaluation_status'];
        $tuan_state = $tourOrder['tuan_state'];
        $complain_status = $tourOrder['complain_status'];

        $order_ican=array(
            'payment'		=> false,//付款
            'cancel' 	=> false,//取消订单
            'delete'    => false,//删除订单（逻辑）
            'refound'		=> false,//退款
            'cancel_refound'	=> false,//取消退款
            'complain'=>false,  //投诉
            'evaluate'		=> false,//评价
        );

        if(!$tourOrder){
            return $order_ican;
        }

        switch($tourOrder['extension']){
            case 'normal':

                //订单相关动作
                if($order_status == TOUR_ORDER_CANCELED || $order_status == TOUR_ORDER_REFUND || $order_status == TOUR_ORDER_FINISHED){
                    $order_ican['delete'] = true;
                }

                if($order_status ==TOUR_ORDER_PENDING){//11：等待付款
                    $order_ican['cancel'] = true;
                    $order_ican['payment'] = true;
                }else if($order_status ==TOUR_ORDER_ACCEPTED){//20：待出行，可退款

                    //退款特殊处理
                    $tour_refund_deadline = app('maqu.config')->getConfig('tour_refund_deadline');

                    //特别说明:
                    //  这里不用gmtime是因为open_date存的时间是日历控件选择的时间 譬如:2017/05/20 00:00;00
                    $open_date = $tourOrder->tourOrderTour->open_date;
                    $now = time();
                    if($now>($open_date- $tour_refund_deadline*24*60*60)){
                        $order_ican['refound'] = false;
                    } else {
                        $order_ican['refound'] = true;
                    }
                }else if($order_status ==TOUR_ORDER_REFUNDING){//21：用户申请退款，可取消
//                    $order_ican['cancel_refound'] = true;
//                    $order_ican['complain'] = true;
                }else if($order_status ==TOUR_ORDER_FINISHED){//40：交易完成
                    if($evaluation_status == 0){
                        $order_ican['evaluate'] = true;
                    }
                    if($complain_status == 0){
                        $order_ican['complain'] = true;
                    }
                        $order_ican['delete'] = true;

                }

                break;
            case 'groupbuy':

                //订单相关动作
                if($order_status == TOUR_ORDER_CANCELED || $order_status == TOUR_ORDER_REFUND || $order_status == TOUR_ORDER_FINISHED){
                    $order_ican['delete'] = true;
                }
                if($order_status ==TOUR_ORDER_PENDING){//11：等待付款
                    $order_ican['cancel'] = true;
                    $order_ican['payment'] = true;
                }else if($order_status == TOUR_ORDER_SUBMITTED || ($order_status ==TOUR_ORDER_ACCEPTED && ($tuan_state ==TUAN_STATE_SUCCESS  || $tuan_state==TUAN_STATE_WAITE))){//20：待出行 已成团，可退款

                    //退款特殊处理
                    $tour_refund_deadline = app('maqu.config')->getConfig('tour_refund_deadline');

                    //特别说明:
                    //  这里不用gmtime是因为open_date存的时间是日历控件选择的时间 譬如:2017/05/20 00:00;00
                    $open_date = $tourOrder->tourOrderTour->open_date;

                    $now = time();
                    if($now>($open_date- $tour_refund_deadline*24*60*60)){
                        $order_ican['refound'] = false;
                    } else {
                        $order_ican['refound'] = true;
                    }
                }else if($order_status ==TOUR_ORDER_REFUNDING){//21：用户申请退款，可取消
//                    $order_ican['cancel_refound'] = true;
                    $order_ican['complain'] = true;
                }else if($order_status ==TOUR_ORDER_FINISHED){//40：交易完成
                    if($evaluation_status == 0){
                        $order_ican['evaluate'] = true;
                    }else{
                        $order_ican['delete'] = true;
                    }
                }

                break;
        }
        return $order_ican;
    }

    /**获取订单详情
     * @param $user_id
     * @param $order_id
     * @param string $extension
     * @return array
     */
    public function getTourOrderDetail($user_id,$order_id){
        //获取订单列表数据
        $query = TourOrder::where('order_id',$order_id)
            ->where('buyer_id',$user_id)
            ->where("delflg_buyer",NO)
            ->with('tourOrderTour.tour','tourOrderTour.tourSchedule');

        $orderInfo = $query->with(['tourOrderExtm','tourOrderTour'=>function($query){
            $query->select('order_id','tour_id','schedule_id','tour_name','tour_image','open_date','peoples_a','peoples_c','singlebuy_config','groupbuy_config','options');
        },'tourTuanData'=>function($query){
            $query->select('order_id','copies','tuan_id');
        },'tourTuanData.tourTuan'=>function($query){
            $query->select('tuan_id','copy_price','state');
        }])
            ->where('order_id',$order_id)
            ->where('buyer_id',$user_id)
            ->where("delflg_buyer",NO)
            ->select('order_id','order_sn','extension','seller_id','seller_name','status','travelers_amount','options_amount','order_amount','evaluation_status','complain_status','add_time','pay_time','payment_name','postscript')
            ->first();

        if(!$orderInfo){
            return $this->failure('未找到对应的订单数据');
        }
        $time = DB::table('config')->where('code','order_info_live_time_tour')->value('value');//未支付订单存活时间商品 配置

        $orderInfo->tourOrderExtm->travel_peoples = json_decode($orderInfo->tourOrderExtm->travel_peoples);
        $orderInfo->tourOrderTour->open_date_fmt = local_date_ymd($orderInfo->tourOrderTour->open_date);
        $orderInfo->tourOrderTour->tour_image = complete_url($orderInfo->tourOrderTour->tour_image);
        $orderInfo->tourOrderTour->singlebuy_config = json_decode($orderInfo->tourOrderTour->singlebuy_config);
        $orderInfo->tourOrderTour->groupbuy_config = json_decode($orderInfo->tourOrderTour->groupbuy_config);
        $orderInfo->tourOrderTour->options = json_decode($orderInfo->tourOrderTour->options);
        $orderInfo->end_time =   $orderInfo->end_time - gmtime();//到期时间(秒)
        $orderInfo->add_time = local_date_ymdhis($orderInfo->add_time);
        $orderInfo->pay_time = local_date_ymdhis($orderInfo->pay_time);
        $orderInfo->ican = self::tourOrder_ican($orderInfo);
        //是否投诉
        if($orderInfo->complain_status == 1){
            $complain = DB::table('complain')->where('product_type','tour')->where('order_id',$orderInfo->order_id)->first();

            if($complain->pictures && count($complain->pictures)>0){
                $images = json_decode($complain->pictures,true);
            }
            if (is_array($images) && count($images)>0)
            {
                foreach($images as $image){
                    $imagearr[] = complete_url($image);
                }
                $complain->pictures= $imagearr;
            }else{
                $complain->pictures='';
            }
            $complain->create_at = local_date_ymd($complain->create_at);
            $complain->update_at = local_date_ymd($complain->update_at);
            $orderInfo->complain = $complain;
        }else{
            $orderInfo->complain = '';
        }
        if($orderInfo->extension == 'groupbuy'){ //团购订单显示状态由团状态控制
            $tuan_order_text = self::tourTuanStatus($orderInfo->status,$orderInfo->tourTuanData->tourTuan,$orderInfo->evaluation_status,$orderInfo->complain_status,$orderInfo->order_id);
            $orderInfo->tuan_text = $tuan_order_text['tuan_text'];
            $orderInfo->status_text = $tuan_order_text['status_text'];
            $orderInfo->tuan_state = $orderInfo->tourTuanData->tourTuan->state;
        }else{
            $orderInfo->status_text = self::tourOrderStatus($orderInfo->status,$orderInfo->evaluation_status,$orderInfo->complain_status,$orderInfo->order_id);
        }

        return $this->success($orderInfo);
    }

    /**获取订单详情
     * @param $user_id
     * @param $order_id
     * @param string $extension
     * @return array
     */
    public function getOrderInfo($user_id,$order_id){
        //获取订单列表数据
        $query = TourOrder::where('order_id',$order_id);
        if($user_id){
            $query->where('buyer_id',$user_id)
                ->where("delflg_buyer",NO);
        }

        $orderInfo = $query->with('tourOrderExtm','tourOrderTour','tourOrderTour.tour','tourOrderTour.tourSchedule','tourTuan','tourOrderRefund')->first();

        if(!$orderInfo){
            return $this->failure('未找到对应的订单数据');
        }

        return $this->success($orderInfo);
    }

    /**
     * 买家取消订单
     * @param $user_id
     * @param $order_id
     * @param bool|true $withTrans
     * @return array
     */
    public function cancelTourOrder($user_id,$order_id,$withTrans = true){

        //买家用户信息
        $userInfo = User::find($user_id);

        $tourOrderInfoData = self::getOrderInfo($user_id,$order_id);
        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }

        $tourOrderInfo = $tourOrderInfoData['data'];

        if($tourOrderInfo->status != TOUR_ORDER_PENDING ){
            return $this->failure('只有未支付的订单可取消');
        }
        if($withTrans){
            DB::beginTransaction();
        }
        try {
            $tourOrderInfo->status = TOUR_ORDER_CANCELED;		//0表示订单为取消状态

            /* 更新订单状态 */
            $tourOrderInfo->save();

//            /* 加回商品库存 */ 库存减少修改在支付成功后进行 所以现在无库存变化
//            $orderService->changeStock('+',$id);

            /* 添加订单操作日志 订单从代付款->已取消 */
            $old_status = self::tourOrderStatus(TOUR_ORDER_PENDING);
            $new_status = self::tourOrderStatus(TOUR_ORDER_CANCELED);
            self::addTourOrderLog($order_id,$userInfo->nickname,$old_status,$new_status,"买家取消订单");

            if($withTrans){
                DB::commit();
            }
            return $this->success();

        } catch (\Exception $e) {
            if($withTrans){
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('处理错误，暂时无法取消订单');
        }
    }

    /**
     * 买家取消订单
     * @param $user_id
     * @param $order_id
     * @param bool|true $withTrans
     * @return array
     */
    public function deleteTourOrder($user_id,$order_id,$withTrans = true){

        //买家用户信息
        $userInfo = User::find($user_id);

        $tourOrderInfoData = self::getOrderInfo($user_id,$order_id);
        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }

        $tourOrderInfo = $tourOrderInfoData['data'];

        /* 只有已取消或者已退款或者已完成的订单可以删除 */
        if($tourOrderInfo->status!=TOUR_ORDER_CANCELED && $tourOrderInfo->status!=TOUR_ORDER_REFUND && $tourOrderInfo->status!=TOUR_ORDER_FINISHED){
            return $this->failure('该订单不可删除');
        }

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            $tourOrderInfo->status = TOUR_ORDER_DELETED;
            $tourOrderInfo->delflg_buyer = ORDER_DELETE_NOTE;

            /* 更新订单状态 */
            $tourOrderInfo->save();

            /* 添加订单操作日志 订单删除 */
            $old_status = self::tourOrderStatus($tourOrderInfo->state);
            $new_status = self::tourOrderStatus(TOUR_ORDER_DELETED);
            self::addTourOrderLog($order_id,$userInfo->nickname,$old_status,$new_status,"买家删除订单");

            if($withTrans){
                DB::commit();
            }
            return $this->success();

        } catch (\Exception $e) {
            if($withTrans){
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('处理错误，暂时无法删除订单');
        }
    }

    public function evaluationTourOrder($user_id,$order_id,$evaluation,$comment,$evaluation_images,$anonymous,$withTrans = true){
        //买家用户信息
        $userInfo = User::find($user_id);

        $tourOrderInfoData = self::getOrderInfo($user_id,$order_id);
        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }

        $tourOrderInfo = $tourOrderInfoData['data'];

        if($tourOrderInfo->status != TOUR_ORDER_FINISHED){
            return $this->failure("该订单不可评价");
        }

        if($tourOrderInfo->evaluation_status == EVALUATE_YES){
            return $this->failure("该订单已评价过，不可重复评价");
        }

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            $tourOrderInfo->evaluation_status = EVALUATE_YES;
            $tourOrderInfo->evaluation_time = gmtime();
            $tourOrderInfo->anonymous = $anonymous;

            /* 更新订单状态 */
            $tourOrderInfo->save();

            $tourOrderEvaluation = new TourOrderEvaluation();
            $tourOrderEvaluation->tour_id = $tourOrderInfo->tourOrderTour->tour_id;
            $tourOrderEvaluation->order_id = $tourOrderInfo->order_id;
            $tourOrderEvaluation->buyer_id = $tourOrderInfo->buyer_id;
            $tourOrderEvaluation->buyer_name = $tourOrderInfo->buyer_name;
            $tourOrderEvaluation->buyer_avatar = $userInfo->portrait;
            $tourOrderEvaluation->evaluation_score = $evaluation;
            $tourOrderEvaluation->evaluation_comment = $comment;
            $tourOrderEvaluation->pictures = json_encode($evaluation_images);
            $tourOrderEvaluation->anonymous = $anonymous;
            $tourOrderEvaluation->evaluation_time = gmtime();
            $tourOrderEvaluation->save();
            /* 添加订单操作日志 订单从待评价到已完成 */
            $old_status = self::tourOrderStatus(ORDER_FINISHED);
            $new_status = self::tourOrderStatus(ORDER_FINISHED,EVALUATE_YES);
            self::addTourOrderLog($order_id,$userInfo->nickname,$old_status,$new_status,"买家评价订单");
            TourStatistics::where('tour_id',$tourOrderEvaluation->tour_id)->increment('comments');
            //获取对应商品所在地区名称
            $tour_info = DB::table('tour')->where('tour_id',$tourOrderEvaluation->tour_id)->first();
            //评论数据入库用于乡粉分享
            $full_evaluation = array(
                'item_id'  => $tourOrderInfo->tourOrderTour->tour_id,
                'user_id'  => $user_id,
                'evaluation_comment'    => $tourOrderEvaluation->evaluation_comment,
                'pictures'  =>$tourOrderEvaluation->pictures,
                'evaluation_time'  => $tourOrderEvaluation->evaluation_time,
                'evaluation_type'  => 'tour',
                'item_name'=>$tour_info->tour_name,
                'province'=>$tour_info->province,
                'city'=>$tour_info->city,
                'country'=>$tour_info->country,
            );
            DB::table('full_evaluation')->insert($full_evaluation);
            if($withTrans){
                DB::commit();
            }
            return $this->success();

        } catch (\Exception $e) {
            if($withTrans){
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('处理错误，暂时无法评价订单');
        }
    }

    public function complainTourOrder($user_id,$order_id,$link_name,$link_phone,$comment,$complain_images,$type,$withTrans = true){
        //买家用户信息
        $userInfo = User::find($user_id);


        $tourOrderInfoData = self::getOrderInfo($user_id,$order_id);

        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }

        $tourOrderInfo = $tourOrderInfoData['data'];

        if($tourOrderInfo->status != TOUR_ORDER_FINISHED){
            return $this->failure("该订单尚未完成，不可投诉");
        }

        if($tourOrderInfo->complain_status == COMPLAIN_YES){
            return $this->failure("该订单已投诉过，请联系客服查询进度");
        }

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            $tourOrderInfo->complain_status = COMPLAIN_YES;
            $tourOrderInfo->complain_time = gmtime();

            /* 更新订单状态 */
            $tourOrderInfo->save();

            $OrderComplain = new OrderComplain();
            $OrderComplain->item_id = $tourOrderInfo->tourOrderTour->tour_id;
            $OrderComplain->order_id = $tourOrderInfo->order_id;
            $OrderComplain->user_id = $tourOrderInfo->buyer_id;
            $OrderComplain->store_id = $tourOrderInfo->seller_id;
            $OrderComplain->product_type = $type;
            $OrderComplain->link_name = $link_name;
            $OrderComplain->link_phone = $link_phone;
            $OrderComplain->desc = $comment;
            $OrderComplain->pictures = json_encode($complain_images);
            $OrderComplain->create_at = gmtime();
            $OrderComplain->save();

            /* 添加订单操作日志 订单从交易完成到提交投诉信息 */
            $old_status = '交易完成';
            $new_status = '已提交投诉信息';
            self::addTourOrderLog($order_id,$userInfo->nickname,$old_status,$new_status,"买家投诉订单");

            if($withTrans){
                DB::commit();
            }
            return $this->success();

        } catch (\Exception $e) {
            if($withTrans){
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('处理错误，暂时无法投诉');
        }
    }

    /**
     * 更新支付方式
     * @param \stdClass $channel
     * @param TourOrder $tourOrder
     * @param bool|false $withTrans
     * @return array
     */
    public function updateOrderPaymentType(\stdClass $channel,TourOrder $tourOrder,$withTrans=false){
        if($withTrans){
            DB::beginTransaction();
        }
        try{
            $tourOrder->payment_id = $channel->payment_id;
            $tourOrder->payment_name = $channel->payment_name;
            $tourOrder->payment_code = $channel->payment_code;
            $tourOrder->save();
            if($withTrans){
                DB::commit();
            }
            return $this->success();
        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
            return $this->failure('选择支付方式失败');
        }

    }

    /**
     * 修改路线日程的库存，可以是减少也可以是加回
     * @notice 个人购买，库存是在支付完成后减少，团购是在团购成功后统一减少；个人购买退单，库存在同意申请后减少，团购退团不影响（团购只能在团团购成功之前退团）
     * @param string $type
     * @param $schedule_id
     * @param $quantity
     * @param bool|true $withTrans
     */
    public function changeStock($type='-',$schedule_id,$quantity,$withTrans = true)
    {
        if($quantity == 0){
            return;
        }

        /* 获取订单商品列表 */
        $tourSchedule = TourSchedule::find($schedule_id);

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            /* 依次改变库存 */
            if ($type == '-') {
                if($quantity > $tourSchedule->stock){
                    $tourSchedule->stock = 0;
                }else{
                    $tourSchedule->stock-= $quantity;
                }
                $tourSchedule->saled_cnt += $quantity;
                TourStatistics::where('tour_id', $tourSchedule->tour_id)->increment('sales', $quantity);
            } else {
                if($tourSchedule->stock_defined > $tourSchedule->saled_cnt){
                    $tourSchedule->stock+=$quantity;
                }
                $tourSchedule->saled_cnt -= $quantity;
                TourStatistics::where('tour_id', $tourSchedule->tour_id)->decrement('sales', $quantity);
            }
            $tourSchedule->save();

            if($withTrans){
                DB::commit();
            }

        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
        }
    }
//-------------------------------------end by shengl----------------
//-------------------------------------add by yangxy----------------
    /**
     * 乡粉分享
     *
     * @param $location 定位
     * @param $level 获取等级
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getSimpleComments($province,$city,$country,$firstrow,$pagesize){



        $query = DB::table('full_evaluation')
            ->join('member','full_evaluation.user_id','=','member.user_id');
        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }
        $query->select(
            'member.user_id','member.portrait','member.nickname',
            'full_evaluation.item_id','full_evaluation.item_name','full_evaluation.evaluation_type',
            'full_evaluation.evaluation_comment','full_evaluation.evaluation_time'
        );

        $datas = $query->orderBy('full_evaluation.evaluation_time','desc')->skip($firstrow)->take($pagesize)->get();

            if($datas){
                foreach ($datas as $item) {
                    $item->evaluation_time_formatted = local_date_ymd($item->evaluation_time);
                    $item->portrait = complete_url($item->portrait);
                }
            }
        return $this->success($datas);

    }

}
